package com.zhou.common.lib.util;

import com.gargoylesoftware.htmlunit.BrowserVersion;
import com.gargoylesoftware.htmlunit.NicelyResynchronizingAjaxController;
import com.gargoylesoftware.htmlunit.WebClient;
import com.gargoylesoftware.htmlunit.html.HtmlPage;
import com.google.common.collect.Lists;
import lombok.extern.slf4j.Slf4j;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;

import java.io.IOException;
import java.util.List;

@Slf4j
public class ShortcutIconUtilsBack {

    static OkHttpClient client = new OkHttpClient();

    public static byte[] getIcon(String path) {
        byte[] bytes = null;
        Document doc = test(path);
        if (doc != null) {
            String imgPath = getIconUrl(doc, path);
            if (StringUtils.isEmpty(imgPath)) {
                imgPath = HttpUtil.getBasePath(path) + "/favicon.ico";
            }
            if (StringUtils.isNotEmpty(imgPath)) {
                String host = HttpUtil.getHost(imgPath);
                String fileName = HttpUtil.getFileName(imgPath);
                Request request = new Request.Builder().url(imgPath).build();
                Response response = null;
                try {
                    response = client.newCall(request).execute();
                    bytes = response.body().bytes();
                } catch (IOException e) {
                    log.error("", e);
                }
                response.close();
            }
        }
        if (bytes != null) {
            log.info("获取成功{}", path);
        } else {
            log.info("获取失败{}", path);
        }
        return bytes;
    }

    public static void main(String[] args) throws Exception {

//        log.info("data={}", data);

        String basePath = "img/";
        List<String> paths = Lists.newArrayList(
                "http://www.baidu.com",
                "http://www.baidu.com",
                "http://172.21.193.133/nacos-test/#/configurationManagement?dataId=&group=&appName=&namespace=&pageSize=&pageNo=",
                "https://fanyi.baidu.com/translate#en/zh/jumbotron",
                "https://v3.bootcss.com/css/#grid",
                "https://cloud.tencent.com/developer/article/2149113"
        );
        for (String path : paths) {
            Document doc = test(path);
            String imgPath = getIconUrl(doc, path);
            String fileName = HttpUtil.getFileName(imgPath);
            Request request = new Request.Builder().url(imgPath).build();
            Response response = client.newCall(request).execute();
            MyFileUtils.fileWriter(response.body().bytes(), basePath + fileName);

        }
    }

    public static String getIconUrl(Document doc, String basePath) {
        Element shortcutIcon = doc.selectFirst("link[rel='shortcut icon']");
        if (shortcutIcon == null) {
            shortcutIcon = doc.selectFirst("link[rel='icon']");
        }
        String url = shortcutIcon.attr("href");
        log.info("parturl={}", url);
        return HttpUtil.getFullUlr(basePath, url);
    }

    public static Document test(String url) {
        final WebClient webClient = new WebClient(BrowserVersion.FIREFOX_ESR);//新建一个模拟谷歌Chrome浏览器的浏览器客户端对象
        webClient.getOptions().setThrowExceptionOnScriptError(false);//当JS执行出错的时候是否抛出异常, 这里选择不需要
        webClient.getOptions().setThrowExceptionOnFailingStatusCode(false);//当HTTP的状态非200时是否抛出异常, 这里选择不需要
        webClient.getOptions().setActiveXNative(false);//不启用ActiveX
        webClient.getOptions().setCssEnabled(false);//是否启用CSS, 因为不需要展现页面, 所以不需要启用
        webClient.getOptions().setJavaScriptEnabled(true); //很重要，启用JS
        webClient.getOptions().setDownloadImages(false);//不下载图片
        webClient.setAjaxController(new NicelyResynchronizingAjaxController());//很重要，设置支持AJAX
        webClient.getOptions().setProxyPolyfillEnabled(false);
        webClient.getOptions().setFetchPolyfillEnabled(false);
        HtmlPage page = null;
        try {
            page = webClient.getPage(url);//尝试加载上面图片例子给出的网页
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            webClient.close();
        }
        webClient.waitForBackgroundJavaScript(10000);//异步JS执行需要耗时,所以这里线程要阻塞30秒,等待异步JS执行结束
        String pageXml = page.asXml();//直接将加载完成的页面转换成xml格式的字符串
        return Jsoup.parse(pageXml);
    }
}
